package controllers

import base.Message
import base.State
import beans.UserInfo
import com.jfinal.aop.Before
import com.jfinal.core.Controller
import com.jfinal.kit.PropKit
import controllers.interceptors.PhoneValidator
import controllers.interceptors.UserTokenCheckValidator
import controllers.interceptors.VerifyCodeValidator
import models.UserInfoM
import services.UserService

class UserController: Controller(){

    companion object{
        val TAG = UserController::class.simpleName!!
        const val PARA_PHONE = "phone"
        const val PARA_VERIFY_CODE = "verify_code"
        const val PARA_TOKEN = "token"
        const val PARA_USER_ID = "user_id"
        const val PARA_SU_USERNAME = "username"
        const val PARA_SU_USER_PWD = "password"
        val prop = PropKit.use("local.properties")
    }

    private val service: UserService by lazy {
        UserService(this)
    }

    @Before(value = arrayOf(PhoneValidator::class, VerifyCodeValidator::class))
    fun register(){
        val phone = get(PARA_PHONE)
        service.registerByPhone(phone)
    }

    fun login(){
        forwardAction("/user/loginByPhone")
    }

    @Before(value = arrayOf(PhoneValidator::class, VerifyCodeValidator::class))
    fun loginByPhone(){
        val phone = get(PARA_PHONE)
        service.loginByPhone(phone)
    }

    @Before(PhoneValidator::class)
    fun verifyCode(){
        val phone = get(PARA_PHONE)
        val code = service.getVerifyCode(phone)
        code?.let {
            setSessionAttr(PARA_VERIFY_CODE, "${code}#${System.currentTimeMillis()}")
        }
    }

    @Before(UserTokenCheckValidator::class)
    fun updateInfo(){
        val userId = UserTokenCheckValidator.getUserId(this)
        val userInfo = UserInfo(
                nick_name = get(UserInfoM.NICK_NAME),
                sign = get(UserInfoM.SIGN),
                sex = getInt(UserInfoM.SEX),
                avatar = get(UserInfoM.AVATAR),
                birthday = get(UserInfoM.BIRTHDAY),
                stu_id = get(UserInfoM.STU_ID),
                college = get(UserInfoM.COLLEGE),
                school = get(UserInfoM.SCHOOL)
        )
        service.updateUserInfo(userId, userInfo)
    }

    @Before(UserTokenCheckValidator::class)
    fun info(){
        val userId = UserTokenCheckValidator.getUserId(this)
        service.getInfo(userId)
    }

    fun userInfo(){
        val userId = getInt(PARA_USER_ID)
        service.findUserInfo(userId)
    }

}